import { CallHandler, ExecutionContext, NestInterceptor, HttpException, HttpStatus } from '@nestjs/common'
import { Observable, throwError } from 'rxjs'
import { catchError } from 'rxjs/operators'

type ApiResponse<T> = {
    code: number
    message: string
    data: T | null
    timestamp: number

}

export class ErrorInterceptor implements NestInterceptor {
    intercept(context: ExecutionContext, next: CallHandler): Observable<ApiResponse<any>> {
        return next.handle().pipe(
            catchError(err => {
                let code: number
                let message: string
                if (err instanceof HttpException) {
                    code = err.getStatus()
                    message = err.getResponse() as string
                } else {
                    code = HttpStatus.INTERNAL_SERVER_ERROR
                    message = "抱歉，服务器内部错误～"
                }
                return throwError(() => {
                    // 创建统一的api数据响应
                    return new HttpException({
                        code, message, data: null, timestamp: Date.now()
                    }, code)
                })
            })
        )

    }
}